package xcmg.device.service.basic;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.basic.ModelMaterialRelationDO;
import xcmg.device.dao.mapper.SaleIntentionDetailMapper;
import xcmg.device.dao.mapper.basic.ModelMaterialRelationMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInventoryMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExcelUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.basic.MaterialsMaintenSearchVO;
import xcmg.device.service.vo.basic.MaterialsVO;
import xcmg.device.service.vo.basic.ModelMaterialRelationAddVO;
import xcmg.device.service.vo.basic.ModelMaterialRelationVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurDetailVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wrg on 2019/5/28.
 */
@Service
public class ModelMaterialService {
    @Autowired
    private ModelMaterialRelationMapper modelMaterialRelationMapper;
    @Autowired
    private FastGenClient genClient;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private MaterialsService materialsService;
    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;
    @Autowired
    private WarehouseDeliveryDetailMapper warehouseDeliveryDetailMapper;
    @Autowired
    private SaleIntentionDetailMapper saleIntentionDetailMapper;
    @Value("${spring.file.download.path}")
    private String filePath;
    private String templateExcelFileName = "CommonQueryImport.xls";
   /* public ErrorCode add(ModelMaterialRelationAddVO addVO, String orgId) throws Exception {
        List<ModelMaterialRelationVO> materialsList = addVO.getMaterialsList();
        String maintenanceModelId = addVO.getMaintenanceModelId();
        addMaterials(orgId, materialsList, maintenanceModelId);
        return ErrorCode.Success;
    }*/

    public ErrorCode update(ModelMaterialRelationAddVO addVO, String orgId) throws Exception {
        List<ModelMaterialRelationVO> materialsList = addVO.getMaterialsList();
        List<String> delIdList = addVO.getDelIdList();
        String maintenanceModelId = addVO.getMaintenanceModelId();

        delMaterials(delIdList);
        addMaterials(orgId, materialsList, maintenanceModelId);

        return ErrorCode.Success;
    }

    private void addMaterials(String orgId, List<ModelMaterialRelationVO> materialsList, String maintenanceModelId) throws Exception {
        if (null == materialsList || materialsList.isEmpty()) {
            return;
        }
        for (ModelMaterialRelationVO modelMaterialRelationVO : materialsList) {
            String materialsNo = modelMaterialRelationVO.getMaterialsNo();
            int i = modelMaterialRelationMapper.countByMaintenanceModelIdAndMate(maintenanceModelId, materialsNo);
            if (i > 0) {
                continue;
            }

            String id = genClient.newGuidText().getValue();
            if (StringUtils.isBlank(id)) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
            ModelMaterialRelationDO record = new ModelMaterialRelationDO();
            BeanUtils.copyProperties(modelMaterialRelationVO, record);
            record.setId(id);
            record.setOrgId(orgId);
            record.setMaintenanceModelId(maintenanceModelId);
            int addCount = modelMaterialRelationMapper.insertSelective(record);
            if (addCount <= 0) {
                throw new Exception(ErrorCode.Failure.getDesc());
            }
        }

    }

    public ErrorCode delMaterials(List<String> delMaterialsNoList) {
        if (null == delMaterialsNoList || delMaterialsNoList.isEmpty()) {
            return ErrorCode.Success;
        }
        for (String id : delMaterialsNoList) {
            modelMaterialRelationMapper.deleteByPrimaryKey(id);
        }
        return ErrorCode.Success;
    }

    public PageCommonVO<ModelMaterialRelationVO> associatedMaterialList(SearchCommonVO<ModelMaterialRelationVO> condition) {
        PageCommonVO result = new PageCommonVO();
        List<ModelMaterialRelationVO> voList = new ArrayList<>();
        ModelMaterialRelationVO relationVO = condition.getFilters();
        relationVO.setMaintenanceModelId(relationVO.getId());

        PageHelperPlus.orderBy("MATERIALS_NO desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ModelMaterialRelationDO> doList = modelMaterialRelationMapper.list(relationVO);
        for (ModelMaterialRelationDO e : doList) {
            ModelMaterialRelationVO model = new ModelMaterialRelationVO();
            BeanUtils.copyProperties(e, model);
            voList.add(model);
        }
        result.setPageInfo(new PageInfo(doList));
        result.setPageInfoList(voList);
        return result;
    }

    public PageCommonVO<ModelMaterialRelationVO> unrelatedMaterialList(SearchCommonVO<ModelMaterialRelationVO> condition) {
        PageCommonVO result = new PageCommonVO();
        List<ModelMaterialRelationVO> voList = new ArrayList<>();

        PageHelperPlus.orderBy("a.MATERIALS_NO desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ModelMaterialRelationDO> doList = modelMaterialRelationMapper.unrelatedMaterialList(condition.getFilters());
        for (ModelMaterialRelationDO e : doList) {
            ModelMaterialRelationVO model = new ModelMaterialRelationVO();
            BeanUtils.copyProperties(e, model);
            voList.add(model);
        }
        result.setPageInfo(new PageInfo(doList));
        result.setPageInfoList(voList);
        return result;
    }

    public PageCommonVO<MaterialsVO> queryMateList(SearchCommonVO<MaterialsMaintenSearchVO> condition) {
        PageCommonVO result = new PageCommonVO();
        List<MaterialsVO> voList = new ArrayList<>();

        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsVO> materialsVOS = modelMaterialRelationMapper.queryMateList(condition.getFilters());
        for (MaterialsVO model : materialsVOS) {
            takeDecimals(model);
            MaterialsVO materialsVO = new MaterialsVO();
            BeanUtils.copyProperties(model, materialsVO);
            materialsVO.setEnableNum(warehouseInventoryMapper.findEnableNum(materialsVO.getMaterialsNo(), condition.getFilters().getOrgId(), condition.getFilters().getWarehouseCode()));
            materialsVO.setDeliveryNum(warehouseDeliveryDetailMapper.findOccupyNum(materialsVO.getMaterialsNo(), condition.getFilters().getOrgId(), condition.getFilters().getWarehouseCode()));
            materialsVO.setIntentionNum(saleIntentionDetailMapper.findOccupyNum(materialsVO.getMaterialsNo(), condition.getFilters().getOrgId()));
            voList.add(materialsVO);
        }
        result.setPageInfo(new PageInfo(materialsVOS));
        result.setPageInfoList(voList);
        return result;
    }

    private static void takeDecimals(MaterialsVO model) {
        if (model.getStandardPrice() != null) {
            model.setStandardPrice(model.getStandardPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getPrice() != null) {
            model.setPrice(model.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getMovingAveragePrice() != null) {
            model.setMovingAveragePrice(model.getMovingAveragePrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
    }

    /**
     * @Author: WangKe
     * @Description: 下载零件批量导入模板
     * @Date: 2018/3/1 0001
     */
    public void download() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateExcelFileName);
    }

    //导入
    public FunctionResult importExcel(InputStream in, String orgId) throws Exception {
        FunctionResult result = new FunctionResult();
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFSheet sheet = wb.getSheetAt(0);

        int totalRow = sheet.getLastRowNum();
        if (totalRow < 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(2).getLastCellNum();
        if (totalCell != 3) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<ThreeGuaranteesPurDetailVO> detailVOList = new ArrayList<>();
        List<ThreeGuaranteesPurDetailVO> errorDetailVOList = new ArrayList<>();
        for (int i = 3; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            ThreeGuaranteesPurDetailVO detailVO = new ThreeGuaranteesPurDetailVO();
            if (curRow == null) {
                continue;
            }
            if (isRowEmpty(curRow)) {
                continue;
            }
            String materialsNo = excelValue(curRow, 1);
            MaterialsVO materialsVO = materialsService.itemByNo(materialsNo, orgId);
            if (materialsVO == null) {
                detailVO.setErrorRow(i + 1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }

            detailVO.setMaterialsNo(materialsVO.getMaterialsNo());
            detailVO.setMaterialsDes(materialsVO.getMaterialsDes());
            detailVOList.add(detailVO);
        }

        if (errorDetailVOList.isEmpty()) {
            result.setValue(detailVOList);
            result.setCode(ErrorCode.Success);
        } else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private String excelValue(HSSFRow curRow, Integer line) {
        Cell cell = curRow.getCell(line);
        String cellValue = "";
        if (null != cell) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    DecimalFormat df = new DecimalFormat("0");
                    cellValue = df.format(cell.getNumericCellValue());
                    break;

                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    cellValue = cell.getStringCellValue();
                    break;

                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    cellValue = cell.getBooleanCellValue() + "";
                    break;

                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    cellValue = cell.getCellFormula() + "";
                    break;

                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    cellValue = "";
                    break;

                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    cellValue = "";
                    break;

                default:
                    cellValue = "";
                    break;
            }
        }
        return cellValue;
    }

    private boolean isRowEmpty(HSSFRow row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            HSSFCell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && !yb.ecp.fast.infra.util.StringUtil.isNullOrSpace(ExcelUtil.getCellStringValue(cell))) {
                return false;
            }
        }
        return true;
    }
}
